package com.example.myapplication.ui.movie

//import com.example.myapplication.ui.movie.DateAdapter.OnRecyclerItemClickListener
import android.content.Intent
import android.graphics.Color
import android.graphics.ColorSpace
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.MovieDetailsActivity
import com.example.myapplication.R
import kotlinx.android.synthetic.main.activity_select_cinema.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.net.URLEncoder
import kotlin.concurrent.thread


class SelectCinemaActivity : AppCompatActivity() {
     var dateList = ArrayList<Date_info>()
     var cinemalist = ArrayList<Cinema_info>()
    val sever_ip = "192.168.43.8"
    val sever_ip2 = "192.168.43.223"
    val searchCinemaDate_jsp = "http://${sever_ip}:8080/JspForAndroid/searchCinemaDate.jsp"
    val searchCinemaByDate_jsp = "http://${sever_ip}:8080/JspForAndroid/searchCinemaByDate.jsp"
//    val searchCinemaDate_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/searchCinemaDate.jsp"
//    val searchCinemaByDate_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/searchCinemaByDate.jsp"
    private var mRecyclerView: RecyclerView? = null
    private var mAdapter: DateAdapter? = null
    private var mRecyclerView2: RecyclerView? = null
    private var mAdapter2: CinemaAdapter? = null

    var movie_Name:String = ""
    public var now_date:String = ""
    var movie_liked = "false"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_select_cinema)
        //setSupportActionBar(toolbar)

        movie_Name = intent.getStringExtra("movie_name").toString()
        select_cinema_movie.text = movie_Name
        //movie_liked = intent.getStringExtra("movie_liked").toString()

        Log.d("dasd","movie_liked = ${movie_liked}, movie_name = ${movie_Name}")
        if (movie_liked == "false"){
            select_cinema_collect.setImageResource(R.drawable.choise_movie_sc)
        }
        else if (movie_liked == "true"){
            select_cinema_collect.setImageResource(R.drawable.choise_movie_sc_clicked)
        }
        select_cinema_collect.setOnClickListener {
            if (movie_liked == "false"){
                movie_liked = "true"
                select_cinema_collect.setImageResource(R.drawable.choise_movie_sc_clicked)
            }
            else if (movie_liked == "true"){
                movie_liked = "false"
                select_cinema_collect.setImageResource(R.drawable.choise_movie_sc)
            }


        }

        //日期，横线RecyView
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        mRecyclerView = findViewById(R.id.RecyView_Date)
        mRecyclerView?.layoutManager = layoutManager
        mAdapter = DateAdapter(dateList, applicationContext)
        mRecyclerView?.setAdapter(mAdapter)

        val layoutManager2 = LinearLayoutManager(this)
        mRecyclerView2 = findViewById(R.id.RecyView_Cinema)
        mRecyclerView2?.layoutManager = layoutManager2
        mAdapter2 = CinemaAdapter(cinemalist, applicationContext, movie_Name)
        mRecyclerView2?.setAdapter(mAdapter2)

        initDates()//初始化日期
        Log.d("ttt:", "dateList.size = ${dateList.size}, now_date = ${now_date}")
        //now_date = dateList[0].date
        initCinemas()


        mAdapter!!.setOnKotlinItemClickListener(object : DateAdapter.IKotlinItemClickListener{
            override fun onItemClickListener(position: Int) {
               // Toast.makeText(applicationContext, "you click ${position}", Toast.LENGTH_LONG).show()
                var i = 0
                while (i < dateList.size){
                    dateList[i].clicked = false
                    i++
                }
                dateList[position].clicked = true
               //Toast.makeText(applicationContext, "you click ${position}, movie_name = ${movie_Name}" +
                        //"now_date = ${dateList[position].date}", Toast.LENGTH_LONG).show()
                mAdapter?.notifyDataSetChanged()
                now_date = dateList[position].date


                //更新影院列表
                getAllTrainInfoJson3(now_date)
                mRecyclerView2?.setAdapter(mAdapter2)
            }
        })

        select_cinema_back.setOnClickListener {
            val intent = Intent(this, MovieDetailsActivity::class.java)
            setResult(1, intent)
            finish()
        }
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.backup -> Toast.makeText(this, "You clicked Backup", Toast.LENGTH_LONG).show()
            R.id.search -> Toast.makeText(this, "You clicked Search", Toast.LENGTH_LONG).show()
            R.id.share -> Toast.makeText(this, "You clicked Share", Toast.LENGTH_LONG).show()
        }
        return true
    }
    //toolbar结束



    private fun initDates(){
        /*dateList.add(Date_info("12月10号", true))
        dateList.add(Date_info("12月10号", false))
        dateList.add(Date_info("12月10号", false))
        dateList.add(Date_info("12月10号", false))*/

        getAllTrainInfoJson()

    }

    private fun initCinemas(){
        Log.d("ttt2222:",  "now_date = ${now_date}")
        /*cinemalist.add(Cinema_info("星空国际永城", "临安区锦城临安宝龙广场",
            "近期场次:18:00", 43.3, 3.4))
        cinemalist.add(Cinema_info("星空国际永城", "临安区锦城临安宝龙广场",
            "近期场次:18:00", 43.3, 3.4))
        cinemalist.add(Cinema_info("星空国际永城", "临安区锦城临安宝龙广场",
            "近期场次:18:00", 43.3, 3.4))
        cinemalist.add(Cinema_info("星空国际永城", "临安区锦城临安宝龙广场",
            "近期场次:18:00", 43.3, 3.4))
        cinemalist.add(Cinema_info("星空国际永城", "临安区锦城临安宝龙广场",
            "近期场次:18:00", 43.3, 3.4))
        cinemalist.add(Cinema_info("星空国际永城", "临安区锦城临安宝龙广场",
            "近期场次:18:00", 43.3, 3.4))
        cinemalist.add(Cinema_info("星空国际永城", "临安区锦城临安宝龙广场",
            "近期场次:18:00", 43.3, 3.4))*/
        getAllTrainInfoJson2()

    }

    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                val requestBody = FormBody.Builder()
                    .add("movie_Name", URLEncoder.encode(movie_Name,"UTF-8"))
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(searchCinemaDate_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson(responseData)
                if (responseData != null){
                    runOnUiThread{
                        //修改布局
                       // mAdapter?.notifyDataSetChanged()

                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson(jsonData:String?):String{
        var builder = StringBuilder()
        val tempList = ArrayList<Date_info>()
        try {
            //json数组
            var temp_String = ""
            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            dateList.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()) {
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                 temp_String = jsonObject.getString("dates")
            }
                builder.clear()
                var substring = temp_String.substring(0, temp_String.length)
                val result: List<String> = substring.split(",")
                for (r in result) {
                    builder.append("$r--")
                    tempList.add(Date_info(r, false))
                }
                //默认选择第一个
            dateList.addAll(tempList)
            dateList[0].clicked = true
            now_date = dateList[0].date
            //initCinemas()
            mAdapter?.notifyDataSetChanged()
            //getAllTrainInfoJson2()

//            Looper.prepare()
//            Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show()
//            Looper.loop()
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }


    private fun getAllTrainInfoJson2(){
        thread {
            try {
                val client = OkHttpClient()

                val requestBody = FormBody.Builder()
                    .add("movie_Name", URLEncoder.encode(movie_Name,"UTF-8"))
                    .add("date", URLEncoder.encode("12月10号","UTF-8"))
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(searchCinemaByDate_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson2(responseData)
                if (responseData != null){
                    runOnUiThread{//????

                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson2(jsonData:String?):String{
        var builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            var tempList = ArrayList<Cinema_info>()

            //清空原来的子项
            cinemalist.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()) {
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val cinema_name = jsonObject.getString("cinema_name")
                val cinema_address = jsonObject.getString("cinema_address")
                val cinema_recenttime = jsonObject.getString("cinema_recenttime")
                val cinema_price = jsonObject.getDouble("cinema_price")
                val cinema_distance = jsonObject.getDouble("cinema_distance")
                builder.append("$cinema_name--$cinema_address--$cinema_recenttime--$cinema_price--$cinema_distance")

                cinemalist.add(Cinema_info(cinema_name, cinema_address,cinema_recenttime,cinema_price,cinema_distance))

            }
            Looper.prepare()
            Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show()
            Looper.loop()
            //cinemalist.addAll(tempList)
            mAdapter2?.notifyDataSetChanged()

            // mAdapter2?.notifyDataSetChanged()
        }catch (e: Exception){
            e.printStackTrace()
        }
        return builder.toString()
    }

    private fun getAllTrainInfoJson3(now_date:String){
        thread {
            try {
                val client = OkHttpClient()

                val requestBody = FormBody.Builder()
                    .add("movie_Name", URLEncoder.encode(movie_Name,"UTF-8"))
                    .add("date", URLEncoder.encode(now_date,"UTF-8"))
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(searchCinemaByDate_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson3(responseData)
                if (responseData != null){
                    runOnUiThread{//????

                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson3(jsonData:String?):String{
        var builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            var tempList = ArrayList<Cinema_info>()

            //清空原来的子项
            cinemalist.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()) {
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val cinema_name = jsonObject.getString("cinema_name")
                val cinema_address = jsonObject.getString("cinema_address")
                val cinema_recenttime = jsonObject.getString("cinema_recenttime")
                val cinema_price = jsonObject.getDouble("cinema_price")
                val cinema_distance = jsonObject.getDouble("cinema_distance")
                builder.append("$cinema_name--$cinema_address--$cinema_recenttime--$cinema_price--$cinema_distance")

                cinemalist.add(Cinema_info(cinema_name, cinema_address,cinema_recenttime,cinema_price,cinema_distance))

            }
            Looper.prepare()
            Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show()
            Looper.loop()
            //cinemalist.addAll(tempList)
            mAdapter2?.notifyDataSetChanged()
            // mAdapter2?.notifyDataSetChanged()
        }catch (e: Exception){
            e.printStackTrace()
        }
        return builder.toString()
    }

}

